package com.ywjt.platformbusiness.store.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.classify.adapter.ClassifyTypeAdapter;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.home.CommonModel;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.store.fragment.StoreClassifyFragment;
import com.ywjt.platformbusiness.store.model.ClassifyListModel;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.ToastUtil;
import com.ywjt.platformbusiness.widget.BaseViewPager;
import com.ywjt.platformbusiness.widget.CenterAddNewTypeDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassifyActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView rcType;
    private LinearLayout llAddClass;
    private ImageView ivBack;
    private BaseViewPager viewPager;
    private MainAdapter adapter;
    private List<Fragment> fragmentList;
    private List<CommonModel> mTitleList;
    private ClassifyTypeAdapter typeAdapter;
    private int type=0;


    private String newTypeName="";
    private String typeId="";
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.llAddClass:
                //新建分类
                if (viewPager.getCurrentItem()==0){
                    //在全部分类
                    Toast.makeText(ClassifyActivity.this,"请选择您要新建的分类的父类",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    CenterAddNewTypeDialog newTypeDialog=new CenterAddNewTypeDialog(ClassifyActivity.this);
                    newTypeDialog.setClicklistener(new CenterAddNewTypeDialog.ClickListenerInterface() {
                        @Override
                        public void sure(String typename) {
                            //在此调用接口创建新的分类
                            createNewType(typename);
                            newTypeDialog.dismiss();
                        }
                    });
                    newTypeDialog.show();
                }
                break;
        }
    }

    public static void actionStart(Context context,int type) {
        Intent intent = new Intent(context, ClassifyActivity.class);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.classify_index;
    }

    public void initView(){
        type=getIntent().getIntExtra("type",type);
        rcType=findViewById(R.id.rcType);
        ivBack=findViewById(R.id.ivBack);
        ivBack.setVisibility(View.VISIBLE);
        viewPager=findViewById(R.id.viewPager);
        llAddClass=findViewById(R.id.llAddClass);
        llAddClass.setVisibility(View.VISIBLE);
        llAddClass.setOnClickListener(this::onClick);
        ivBack.setOnClickListener(this::onClick);
        mTitleList=new ArrayList<>();
        fragmentList=new ArrayList<>();
    }

    @Override
    protected void initData() {
        getTypeData();
    }


    private void getTypeData() {
        new HttpRequest(getContext()).doGet(UrlConstants.classify_getAllClassifyByUser, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), ClassifyListModel.class);
                        if (obj instanceof ClassifyListModel) {
                            ClassifyListModel model = (ClassifyListModel) obj;
                            if (model.getResult().size()>0){
                                mTitleList=new ArrayList<>();
                                fragmentList=new ArrayList<>();
                                for (int i=0;i<model.getResult().size();i++){
                                    if (i==0){
                                        mTitleList.add(new CommonModel(model.getResult().get(i).getName(),true));
                                    }else {
                                        mTitleList.add(new CommonModel(model.getResult().get(i).getName(),false));
                                    }
                                    fragmentList.add(StoreClassifyFragment.newInstance(type,model.getResult().get(i).getId()));
                                }
                                adapter=new MainAdapter(getSupportFragmentManager());
                            viewPager.setAdapter(adapter);
                            viewPager.setScrollable(false);
                            typeAdapter=new ClassifyTypeAdapter(mTitleList);
                            rcType.setAdapter(typeAdapter);
                            rcType.setLayoutManager(new LinearLayoutManager(ClassifyActivity.this));

                            typeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    for (int i=0;i<mTitleList.size();i++){
                                            mTitleList.get(i).setSelected(false);
                                        }
                                        mTitleList.get(position).setSelected(true);
                                        adapter.notifyDataSetChanged();
                                        viewPager.setCurrentItem(position);
                                        typeId=model.getResult().get(position).getId();
                                }
                            });
                           }
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void createNewType(String name) {
        Map jsonObject=new HashMap<>();
            jsonObject.put("id",typeId);
            jsonObject.put("name",name);
        new HttpRequest(getContext()).doGet(UrlConstants.classify_addNewCommodityClassify, "",jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        ToastUtil toastUtil=new ToastUtil(ClassifyActivity.this,R.layout.popu_success1,"创建分类成功，请等待审核",1);
                        toastUtil.show();
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    //适配器
    public class MainAdapter extends FragmentPagerAdapter {

        public MainAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        //获取标题
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position).getStr();
        }
    }

}